// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//

#include <cantor/unresolved/unresolved.h>
#include <cantor/transform/transform.h>
#include <merak/proto/pb_to_json.h>
#include <merak/proto/json_to_pb.h>
#include <cantor/unresolved/dispatch_expr.h>

namespace cantor::unresolved {

    turbo::Status Unresolved::parse_query(const std::string & sql) {
        cantor::transform::Transform transform;
        cantor::parser::SqlParser parser;
        parser.parse(sql);
        transform.resolve_ast(&parser);
        if (transform.status.ok()) {
            _statements = std::move(transform.stmts);
            setup_result();
        }
        return transform.status;
    }

    turbo::Status Unresolved::parse_expressions(const std::string &exprs) {
        auto query = "SELECT " + exprs;
        return parse_query(query);
    }

    turbo::Result<std::string> Unresolved::to_json() const {
        std::string json;
        TURBO_RETURN_NOT_OK(merak::proto_message_to_json(_statements, &json));
        return json;
    }

    turbo::Status Unresolved::from_json(const std::string &j) {
        cantor::pb::ast::Statements s;
        TURBO_RETURN_NOT_OK(merak::json_to_proto_message(j, &s));
        _statements = std::move(s);
        setup_result();
        return turbo::OkStatus();
    }

    void Unresolved::setup_result() {
        result.clear();
        for (const auto &stmt : _statements.statements()) {
            UnresolvedStatement st;
            st.attach(&stmt);
            result.push_back(std::move(st));
        }
    }
}  // namespace cantor::unresolved
